import { useEffect, useState } from 'react'

interface PerformanceMetrics {
    fcp: number | null // First Contentful Paint
    lcp: number | null // Largest Contentful Paint
    fid: number | null // First Input Delay
    cls: number | null // Cumulative Layout Shift
    ttfb: number | null // Time to First Byte
}

const PerformanceMonitor: React.FC = () => {
    const [metrics, setMetrics] = useState<PerformanceMetrics>({
        fcp: null,
        lcp: null,
        fid: null,
        cls: null,
        ttfb: null
    })

    useEffect(() => {
        // 获取性能指标
        const getPerformanceMetrics = () => {
            const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
            const paintEntries = performance.getEntriesByType('paint')

            // FCP (First Contentful Paint)
            const fcpEntry = paintEntries.find(entry => entry.name === 'first-contentful-paint')
            const fcp = fcpEntry ? fcpEntry.startTime : null

            // TTFB (Time to First Byte)
            const ttfb = navigation ? navigation.responseStart - navigation.requestStart : null

            // LCP (Largest Contentful Paint) - 需要观察器
            let lcp: number | null = null
            if ('PerformanceObserver' in window) {
                const lcpObserver = new PerformanceObserver((list) => {
                    const entries = list.getEntries()
                    const lastEntry = entries[entries.length - 1]
                    lcp = lastEntry.startTime
                })
                lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] })
            }

            // FID (First Input Delay) - 需要观察器
            let fid: number | null = null
            if ('PerformanceObserver' in window) {
                const fidObserver = new PerformanceObserver((list) => {
                    const entries = list.getEntries()
                    entries.forEach((entry: any) => {
                        fid = entry.processingStart - entry.startTime
                    })
                })
                fidObserver.observe({ entryTypes: ['first-input'] })
            }

            // CLS (Cumulative Layout Shift) - 需要观察器
            let cls: number | null = null
            if ('PerformanceObserver' in window) {
                let clsValue = 0
                const clsObserver = new PerformanceObserver((list) => {
                    const entries = list.getEntries()
                    entries.forEach((entry: any) => {
                        if (!entry.hadRecentInput) {
                            clsValue += entry.value
                        }
                    })
                    cls = clsValue
                })
                clsObserver.observe({ entryTypes: ['layout-shift'] })
            }

            setMetrics({
                fcp,
                lcp,
                fid,
                cls,
                ttfb
            })
        }

        // 延迟获取指标，确保页面完全加载
        const timer = setTimeout(getPerformanceMetrics, 2000)

        return () => clearTimeout(timer)
    }, [])

    // 性能评分
    const getPerformanceScore = (metric: number | null, thresholds: { good: number; poor: number }) => {
        if (metric === null) return 'N/A'
        if (metric <= thresholds.good) return 'Good'
        if (metric <= thresholds.poor) return 'Needs Improvement'
        return 'Poor'
    }

    const getScoreColor = (score: string) => {
        switch (score) {
            case 'Good': return '#52c41a'
            case 'Needs Improvement': return '#faad14'
            case 'Poor': return '#ff4d4f'
            default: return '#666'
        }
    }

    return (
        <div style={{
            position: 'fixed',
            top: '10px',
            right: '10px',
            background: 'rgba(0, 0, 0, 0.8)',
            color: 'white',
            padding: '16px',
            borderRadius: '8px',
            fontSize: '12px',
            fontFamily: 'monospace',
            zIndex: 9999,
            minWidth: '200px'
        }}>
            <h4 style={{ margin: '0 0 12px 0', fontSize: '14px' }}>Performance Metrics</h4>

            <div style={{ marginBottom: '8px' }}>
                <span>FCP: </span>
                <span style={{
                    color: getScoreColor(getPerformanceScore(metrics.fcp, { good: 1800, poor: 3000 }))
                }}>
                    {metrics.fcp ? `${Math.round(metrics.fcp)}ms` : 'N/A'}
                </span>
            </div>

            <div style={{ marginBottom: '8px' }}>
                <span>LCP: </span>
                <span style={{
                    color: getScoreColor(getPerformanceScore(metrics.lcp, { good: 2500, poor: 4000 }))
                }}>
                    {metrics.lcp ? `${Math.round(metrics.lcp)}ms` : 'N/A'}
                </span>
            </div>

            <div style={{ marginBottom: '8px' }}>
                <span>FID: </span>
                <span style={{
                    color: getScoreColor(getPerformanceScore(metrics.fid, { good: 100, poor: 300 }))
                }}>
                    {metrics.fid ? `${Math.round(metrics.fid)}ms` : 'N/A'}
                </span>
            </div>

            <div style={{ marginBottom: '8px' }}>
                <span>CLS: </span>
                <span style={{
                    color: getScoreColor(getPerformanceScore(metrics.cls, { good: 0.1, poor: 0.25 }))
                }}>
                    {metrics.cls ? metrics.cls.toFixed(3) : 'N/A'}
                </span>
            </div>

            <div>
                <span>TTFB: </span>
                <span style={{
                    color: getScoreColor(getPerformanceScore(metrics.ttfb, { good: 800, poor: 1800 }))
                }}>
                    {metrics.ttfb ? `${Math.round(metrics.ttfb)}ms` : 'N/A'}
                </span>
            </div>
        </div>
    )
}

export default PerformanceMonitor
